<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
  <head>
    <title>添加采购退货订单</title>
    <script type="text/javascript">
      Ext.onReady(function(){
        var purchaseOrderId = Ext.create('Ext.form.field.Hidden', {
          name: 'purchase_order_id',
          value: '<%=params[:id]%>'
        });
        
        //备注
        var desc = Ext.create('Ext.form.field.Text', {
          fieldLabel: '备注',
          name: 'description',
          anchor: '97%'
        });
        
        //供应商
        var vendor = Ext.create('Ext.form.field.Text', {
          fieldLabel: '供应商',
          allowBlank: false,
          readOnly: true,
          name: 'vendor_name',
          anchor: '90%'
        });        

        //要求退货时间
        var returnDate = Ext.create('Ext.form.field.Date', {
          fieldLabel: '退货日期',
          allowBlank: false,
          name: 'return_date',
          format: 'Y-m-d', //格式化日期
          //disabledDays: [0,6],	//不让选择周六，周日
          //disabledDaysText: "周末要休息",
          invalidText: "您输入的日期格式不对，正确格式为2010-01-18",
          blankText: "要求退货日期必须选择",
          emptyText: '退货日期...'
          //anchor: '50%'
        });
        
        //合同号
        var contractNumber = Ext.create('Ext.form.field.Text', {
          fieldLabel: '合同编号',
          allowBlank: true,
          readOnly: true,
          name: 'contract_number',
          anchor: '90%'
        });

        //联系人
        var linkman = Ext.create('Ext.form.field.Text', {
          fieldLabel: '联系人',
          name: 'linkman',
          allowBlank: false
        });
        
        //联系电话
        var phone = Ext.create('Ext.form.field.Text', {
          fieldLabel: '联系电话',
          name: 'phone',
          allowBlank: false
        });

        //税率
        var taxRate = Ext.create('Ext.form.field.Number', {
          fieldLabel: '税率(%)',
          name:"tax_rate",
          allowBlank: false,
          allowDecimals: true,
          minValue: 0,
          maxValue: 100,
          readOnly:true,
          anchor: '90%'
        });

        var deliveryAddress = Ext.create('Ext.form.field.Text', {
          fieldLabel: '送货地址',
          allowBlank: false,
          name: 'delivery_address',
          anchor: '95%'
        });

        //总金额
        var sumAmount = Ext.create('Ext.form.field.Number', {
          fieldLabel: '总金额',
          name:"amount",
          readOnly:true,
          allowBlank: false,
          allowDecimals: true,
          minValue: 0,
          anchor: '90%'
        });
        //--------------------------------------------------------------------------
        //采购订单列表Grid Store
        var purchaseOrderDetailDS = Ext.create('Ext.data.Store', {
          proxy: new Ext.data.HttpProxy({
            url: '/purchase_returned/getPurchaseOrderDetailsByIdForReturned'
          }),
          reader: new Ext.data.JsonReader({
            totalProperty: 'totalProperty',
            root: 'root'
          }, [{
              name: 'id'
            },{
              name: 'number'
            }, {
              name: 'product_name'
            }, {
              name: 'spec'
            }, {
              name: 'unit'
            }, {
              name: 'description'
            }, {
              name: 'unit_price',
              type: 'float'
            }, {
              name: 'quantity',
              mapping: 'balance_quantity',
              type: 'int'
            }, {
              name: 'balance_quantity',
              type: 'int'
            },{
              name: 'product_id'
            },{
              name: 'amount',
              type: 'float'
            },{
              name: 'is_suit',
              mapping: 'is_suit',
              convert:function(value,record){
                if(value == "1"){
                  return "套装";
                }else if(value == "0"){
                  return "单品";
                }
              }
            }])
        });
        purchaseOrderDetailDS.getProxy().extraParams.purchase_order_id = <%=params[:id]%>;
        purchaseOrderDetailDS.load();
        //生成产品Grid的CM

        var cellEditing = Ext.create('Ext.grid.plugin.CellEditing', {
          clicksToEdit: 1
        });
        
        //生成要订单的产品的Grid
        var purchaseOrderDetailGrid = Ext.create('Ext.grid.Panel', {
          store: purchaseOrderDetailDS,
          plugins: [cellEditing],
          columns : [Ext.create('Ext.grid.RowNumberer'),{
              header: 'id',
              dataIndex: 'id',
              width: 30
            },{
              header: '产品名称',
              dataIndex: 'product_name',
              width: 250
            },{
              header: '产品ID',
              dataIndex: 'product_id',
              width: 50,
              hidden: false
            },{
              header: '产品编号',
              dataIndex: 'number',
              width: 90
            },{
              header: '规格',
              dataIndex: 'spec',
              width: 50
            },{
              header: '单位',
              dataIndex: 'unit',
              width: 50
            },{
              header: '数量',
              align: 'right',
              dataIndex: 'quantity',
              field: Ext.create('Ext.form.field.Number', {
                allowBlank: false,
                allowDecimals: false,
                minValue: 1
              }),
              width: 50
            },{
              header: '单价',
              dataIndex: 'unit_price',
              field: Ext.create('Ext.form.field.Number', {
                allowBlank: false,
                allowDecimals: true,
                minValue: 0
              }),
              align: 'right',
              renderer: Ext.util.Format.numberRenderer('0,000.00'),
              width: 60
            },{
              header: '金额',
              dataIndex: 'amount',
              align: 'right',
              renderer: Ext.util.Format.numberRenderer('0,000.00'),
              width: 60
            },{
              header: '套装或单品',
              dataIndex: 'is_suit',
              width: 70
            },{
              header: '备注',
              dataIndex: 'description',
              width: 230,
              field:Ext.create('Ext.form.field.Text', {
                name: 'description',
                anchor: '90%'
              })
            }],
          selModel :Ext.create('Ext.selection.CheckboxModel'),
          width: 1130,
          height: 315,
          //frame: true,
          //title: '进货品种列表',
          //frame: true,
          //plugins: checkColumn,
          
          tbar: [{
              text: '删除',
              iconCls: 'remove',
              handler : function(){
                var records = purchaseOrderDetailGrid.getSelectionModel().getSelection();
                cellEditing.cancelEdit();
                purchaseOrderDetailDS.remove(records);
                
                getSumAmount();
              }
            }]
        });

        //暂时提交按钮
        var submitButton = Ext.create('Ext.Button', {
          text: '提交',
          tooltip: '提交采购退货订单。',
          iconCls: 'icon-save',
          handler: function(){
            if (purchaseReturnedFormPanel.form.isValid()) {
              
              var productsJsonStr = gridStoreToJson(purchaseOrderDetailDS,rejectKeyArray);
              if (purchaseOrderDetailDS.getCount() == 0 || productsJsonStr === ""){
                Ext.MessageBox.show({
                  title: '提示',
                  msg: "您还没有选择有效的产品或选择的产品数量为0！",
                  buttons: Ext.MessageBox.OK,
                  icon: Ext.MessageBox.INFO
                });
                return;
              }
              var allJsonStr = purchaseReturnedFormPanel.getForm().getValues();
              allJsonStr = Ext.JSON.encode(allJsonStr);
              allJsonStr = Ext.util.Format.substr(allJsonStr,0,allJsonStr.length-1);
              allJsonStr = allJsonStr + ",\"products\":" + productsJsonStr + "}";
              //alert(allJsonStr);
              Ext.Ajax.request({
                url : '/purchase_returned/create',
                success : function (result, request) {
                  //Ext.MessageBox.alert("提示","提交成功");
                  newPurchaseReturnedWin.destroy();
                },
                failure : function (result, request){
                  Ext.MessageBox.show({
                    title: '消息',
                    msg: "通讯失败，请从新操作",
                    buttons: Ext.MessageBox.OK,
                    icon: Ext.MessageBox.WARNING
                  });
                  newPurchaseReturnedWin.destroy();
                },
                method : 'POST',
                params : {
                  data : Ext.JSON.encode(allJsonStr),
                  authenticity_token: authToken.getValue()
                }
              });
            }
          }
        });

        //暂时提交按钮
        var closeButton = Ext.create('Ext.Button', {
          text: '关闭',
          tooltip: '关闭当前窗口，并且当前编辑的信息不能提交。',
          iconCls: 'exit',
          handler: function(){
            newPurchaseReturnedWin.destroy();
          }
        });
        
        //采购申请的FormPanel
        var purchaseReturnedFormPanel = Ext.create('Ext.form.Panel', {
          fieldDefaults: {
            labelWidth: 55,
            labelAlign: 'right'
          },
          width: 1143,
          frame : true,
          url: '/purchase_returned/create',
          method: 'GET',
          reader: new Ext.data.JsonReader({
            root: 'root'
          }, [{
              name: 'id'
            }, {
              name: 'vendor_name',
              mapping: 'vendor.name'
            }, {
              name: 'amount'
            }, {
              name: 'description'
            }, {
              name: 'contract_number'
            }, {
              name: 'linkman'
            }, {
              name: 'phone'
            }, {
              name: 'tax_rate'
            }, {
              name: 'delivery_address'
            }]),
          //defaultType: 'textfield',
          items: [{
              layout: 'column',
              xtype: 'container',
              items: [{
                  columnWidth: .3,
                  layout: 'anchor',
                  xtype: 'container',
                  items: [vendor]
                }, {
                  columnWidth: .2,
                  layout: 'anchor',
                  xtype: 'container',
                  items: [returnDate]
                }, {
                  columnWidth: .2,
                  layout: 'anchor',
                  xtype: 'container',
                  items: [contractNumber]
                }, {
                  columnWidth: .2,
                  layout: 'anchor',
                  xtype: 'container',
                  items: [taxRate]
                }]
            },{
              layout: 'column',
              xtype: 'container',
              items: [{
                  columnWidth: .3,
                  layout: 'anchor',
                  xtype: 'container',
                  items: [linkman]
                }, {
                  columnWidth: .2,
                  layout: 'anchor',
                  xtype: 'container',
                  items: [phone]
                },{
                  columnWidth: .5,
                  layout: 'anchor',
                  xtype: 'container',
                  items: [deliveryAddress]
                }]
            },{
              layout: 'column',
              xtype: 'container',
              items: [{
                  columnWidth: 1,
                  layout: 'anchor',
                  xtype: 'container',
                  items: [desc]
                }]
            },{
              layout: 'column',
              xtype: 'container',
              items: [{
                  columnWidth: 1,
                  layout: 'anchor',
                  xtype: 'container',
                  items: [purchaseOrderDetailGrid]
                }]
            },{
              layout: 'column',
              xtype: 'container',
              items: [{
                  columnWidth: 0.3,
                  layout: 'anchor',
                  xtype: 'container',
                  items: [sumAmount]
                }]
            },purchaseOrderId],
          buttons: [submitButton,closeButton]
        });

        purchaseReturnedFormPanel.form.load({
          url: '/purchase_order/getPurchaseOrderById?id=' + <%=params[:id]%>,
          method : 'GET',
          waitMsg: '正在载入数据...',
          success: function(form, action){
          },
          failure: function(form, action){
            Ext.MessageBox.alert('提示信息', '信息加载失败');
          }
        });
        
        purchaseReturnedFormPanel.render('new_purchase_returned');
        //
        purchaseOrderDetailGrid.on('edit', afterEdit, this );


        function afterEdit(editor,obj,options) {

          //不允许退货数，大于采购数
          if(obj.field=="quantity"){
            if (obj.record.get('quantity') > obj.record.get('balance_quantity') || obj.record.get('quantity')  == 0){
              obj.record.set('quantity', obj.record.get('balance_quantity'));
              return;
            }
          }
          
          //
          if(obj.field=="quantity"||obj.field=="unit_price"){
            if(obj.record.get('quantity')>0 && obj.record.get('unit_price') >0){
              obj.record.set('amount',obj.record.get('quantity')*100*obj.record.get('unit_price')/100);
            }else{
              obj.record.set('amount',0);
            }
          }
          getSumAmount();
        }

        function getSumAmount(){
          sumAmount.setValue(0);
          var records = purchaseOrderDetailDS.getRange(0,purchaseOrderDetailDS.getCount());
          for(var i = 0; i< records.length ;i++){
            var record = records[i];
            var amount = record.get('amount');
            if (amount === undefined){
              amount = 0;
            }
            sumAmount.setValue(sumAmount.getValue()+Number(amount));
          }
        }
      })
    </script>
  </head>
  <body>
    <div id="new_purchase_returned"></div>
  </body>
</html>